#include "ProducerMqttAliyun.h"
#ifdef WIN32
#include <Windows.h>
#define usleep(x) Sleep(x)
#else
#include <string>
#include <stdlib.h>
#include <stdio.h>
#endif

#include <time.h>

#include "Log.h"
#include "svc_control.h"

ProducerMqttAliyun::ProducerMqttAliyun(std::map<int, SvcDesc> svcTriples_)
	: running(true)
	, svcTriples(svcTriples_)
	, send_queue(QueueDataSingle<WCacheAliyun>::getInstance())
{
}

ProducerMqttAliyun::~ProducerMqttAliyun()
{
	Print_NOTICE("producer mqtt aliyun thread is outing!\n");
	running = false;
}

void* ProducerMqttAliyun::run()
{
	while (running)
	{
		checkSvcState();
		usleep(100);
	}
	return 0;
}

void ProducerMqttAliyun::checkSvcState()
{
	std::map<int, SvcDesc>::iterator it = svcTriples.begin();
	for (; it != svcTriples.end(); ++it)
	{
		int state = 0;
		SvcQuery((char*)it->second.svc_name.c_str(), state);
		bool valChange = false;
		if (state > 0)
		{
			unsigned int cur_time = static_cast<unsigned int>(time(NULL));
			ServiceState e_state = static_cast<ServiceState>(state);
			if (it->second.svc_state != e_state)
			{
				CLogger::createInstance()->Log(MsgInfo
					,"svc:%s,state:%d is change\n",it->second.svc_name.c_str(), state);
				valChange = true;
				it->second.svc_state = e_state;
				it->second.markT = cur_time + it->second.upLoopTime;
			}else {
				//刷新时变化
				if (it->second.markT<cur_time)
				{
					valChange = true;
					it->second.markT = cur_time + it->second.upLoopTime;
				}
			}
		}
		if (valChange)
		{
			WCacheAliyun wcAliyun(it->first,(int)it->second.svc_state);
			send_queue->add(wcAliyun);
		}
	}
};
